package org.duang.upload;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.common.dto.HeadDto;
import org.duang.common.dto.ReturnDto;
import org.duang.common.exceptios.ServiceException;
import org.duang.config.Config;
import org.duang.config.InstanceFactory;
import org.duang.kit.OSSKit;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.security.SecurityConstant;
import com.security.SecurityHelper;
import com.security.ShiroUser;

@WebServlet(name = "uploadServlet", urlPatterns = { "/webuploader" })
public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory.getLogger(UploadServlet.class);
	private static ConcurrentHashMap<String,String> webUploadFileFlagMap = new ConcurrentHashMap<String,String>();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if (ToolsKit.isEmpty(type)) throw new ServiceException("type is empty!");
		if ("index".equalsIgnoreCase(type)) {
			index(request, response);
		} else if ("submit".equalsIgnoreCase(type)) {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("application/json;charset="+ Config.getEncoding());
			response.setCharacterEncoding(Config.getEncoding());
			ReturnDto<Object> dto = new ReturnDto<Object>();
			HeadDto head = new HeadDto();
			try {
				String userid = getShiroUserId();
				String saveDirectory = webUploadFileFlagMap.get(userid);
				UploadFileRequest uploadFileRequest = new UploadFileRequest(request, saveDirectory);
				request = uploadFileRequest;
				String product = request.getParameter("product");
				String flag = request.getParameter("flag");
				String iszip = request.getParameter("iszip");				
				if (ToolsKit.isEmpty(product) || ToolsKit.isEmpty(flag) || ToolsKit.isEmpty(iszip)) throw new ServiceException("webuploader param is empty!");
				if(!saveDirectory.equals(flag)){throw new ServiceException("saveDirectory is inconsistent");}
				List<UploadFile> files = uploadFileRequest.getUploadFiles();
				String site = "";
				if ("OSS".equalsIgnoreCase(Config.getUploadFileSite())) {
					site = Config.getFileHostSite();
					OSSKit.putImg2OSS(files);
				}
				head.setRet(0);
				head.setMsg(site);
				dto.setHead(head);
				dto.setData(files);
			} catch (Exception e) {
				e.printStackTrace();
				head.setRet(-1);
				head.setMsg("error");
				dto.setHead(head);
				dto.setData(null);
			}
			String fileString = JSON.toJSONString(dto);
			PrintWriter out = response.getWriter();
			out.println(fileString);
			out.flush();
		}
	}

	private void index(HttpServletRequest request, HttpServletResponse response) {
		//必须要开启安全认证及登录后才能使用
		String userid = getShiroUserId();
		if(!Config.getEnadleSecurity() || ToolsKit.isEmpty(userid)) { logger.warn(SecurityConstant.CURRENT_USER_NOT_PERMISSION_ACCESS); return;}
		String product = Config.getProductCode();// request.getParameter("product");
		String flag = request.getParameter("flag");
		String iszip = request.getParameter("iszip");
		if (ToolsKit.isEmpty(product) || ToolsKit.isEmpty(flag) || ToolsKit.isEmpty(iszip)) throw new ServiceException("webuploader param is empty!");
		try{
			webUploadFileFlagMap.put(userid, flag);
			logger.warn("open webupload page...");		
			request.setAttribute("webuploader_product", product);
			request.setAttribute("webuploader_flag", flag);
			request.setAttribute("webuploader_iszip", iszip);
			InstanceFactory.getServletContext().getRequestDispatcher("/WEB-INF/pages/static/webuploader/upload.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.warn(e.getMessage());
			throw new ServiceException(e.getMessage());
		}
	}
	
	private String getShiroUserId(){
		ShiroUser sUser = SecurityHelper.getShiroUser();
		if(ToolsKit.isEmpty(sUser)){
			logger.warn(SecurityConstant.CURRENT_USER_NOT_LOGIN);
			return "";
		}
		return sUser.getUserid();
	}
	

}